#include "textureMgr.h"
#include <d3dx11.h>

TextureMgr* TextureMgr::ins = NULL;
TextureMgr::Garbage TextureMgr::garbage;
TextureMgr::TextureMgr()
{

}
TextureMgr::~TextureMgr()
{
	std::map<std::wstring, ID3D11ShaderResourceView*>::iterator iter = mSRVs.begin();
	for (; iter != mSRVs.end(); ++iter)
	{
		if (iter->second)
		{
			iter->second->Release();
		}
	}
	std::map<std::wstring, ID3D11Texture2D*>::iterator iter2 = mTextures.begin();
	for (; iter2 != mTextures.end(); ++iter2)
	{
		if (iter2->second)
		{
			iter2->second->Release();
		}
	}
	
}

ID3D11ShaderResourceView* TextureMgr::CreateTexture(ID3D11Device* device, const std::wstring& filename)
{
	std::map<std::wstring, ID3D11Texture2D*>::iterator iter = mTextures.find(filename);
	if (iter != mTextures.end())
	{
		std::map<std::wstring, ID3D11ShaderResourceView*>::iterator iter2 = mSRVs.find(filename);
		return iter2->second;		
	}
	else
	{
		// Load the Texture
		ID3D11Texture2D * pTexture2D = NULL;
		ID3D11ShaderResourceView *pSRView = NULL;
		D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
		D3D11_TEXTURE2D_DESC desc;

		// Load the texture and initialize an ID3D11Texture2D object.
		HRESULT hr = D3DX11CreateTextureFromFile(device, filename.c_str(), NULL, NULL, (ID3D11Resource**)&pTexture2D, NULL);
		if (FAILED(hr))
		{
			return NULL;
		}
		// Get a texture description to determine the texture
		// format of the loaded texture.
		pTexture2D->GetDesc(&desc);

		// Fill in the D3D11_SHADER_RESOURCE_VIEW_DESC structure.
		srvDesc.Format = desc.Format;
		srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
		srvDesc.Texture2D.MostDetailedMip = 0;
		srvDesc.Texture2D.MipLevels = desc.MipLevels;

		// Create the shader resource view.
		hr = device->CreateShaderResourceView(pTexture2D, &srvDesc, &pSRView);
		if (FAILED(hr))
		{
			return NULL;
		}

		mTextures.insert(std::pair<std::wstring, ID3D11Texture2D*>(filename, pTexture2D));
		mSRVs.insert(std::pair<std::wstring, ID3D11ShaderResourceView*>(filename, pSRView));

		return pSRView;
	}
}